package asteroids.statements;


import java.util.*;

import be.kuleuven.cs.som.annotate.Basic;

import asteroids.Ship;
import asteroids.expressions.Expression;
import asteroids.types.*;

public class WhileLoopStatement extends ComposedStatement {
	
	private Expression condition;
	private Statement body;

	public WhileLoopStatement(int line, int column, Expression condition, Statement body) {
		super(line, column);
		this.condition = condition;
		this.body = body;
	}
	
	@Basic
	public Expression getCondition() {
		return condition;
	}

	@Basic
	public Statement getBody() {
		return body;
	}

	@Override
	public int getNbOfStatements() {
		return 1;
	}

	@Override
	public Statement getStatementAt(int index) throws IndexOutOfBoundsException {
		if (index == 1)
			return getBody();
		else
			throw new IndexOutOfBoundsException();
	}

	@Override
	public void execute(Ship ship) {
		while(((BooleanType) getCondition().evaluate(ship, ship.getProgram().getGlobals())).getValue()) {
			getBody().execute(ship);
		}
	}

	@Override
	public List<String> getTypeCheckErrors(List<String> typeErrors,	Map<String, Type> globalVariables) {
		typeErrors = getCondition().getTypeCheckErrorsExpressions(typeErrors, globalVariables);
		if(getCondition().evaluate(null, globalVariables).getClass() != BooleanType.class) {
			typeErrors.add("Line: " + getLine() + " Column: " + getColumn() + " - The condition '" + getCondition().toString() + "' is expected to be from the type 'boolean'.");
		}
		typeErrors = getBody().getTypeCheckErrors(typeErrors, globalVariables);
		return typeErrors;
	}
}
